/**
 * create by young (young2f@outlook.com) on 2020/9/12
 */

'use strict';
import React from 'react';
import {connect} from 'dva/index';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Drawer,
  Dropdown,
  Form,
  Input,
  Menu,
  Popconfirm,
  Row,
  Select,
  Statistic,
  Table, Tabs
} from 'antd';

import styles from '../../index.less';
import ModalCreateOrEditProcureOrder from './../modal/ModalCreateOrEditProcureOrder';
import ViewTitle from '../../../components/ViewTitle';
import FormBase from '../../../components/Base/FormBase';
import notify from "../../../components/NotificationExtra";
import {FormField, ModalView, SearchForm} from 'antd-extra';
import moment from 'moment';
import 'moment/locale/zh-cn';
import ModalProcureOrderDetail from "./../modal/ModalProcureOrderDetail";
import {exportExcel} from '../../../utils/excelUtils';
import Icon from "antd/es/icon";
import ModalCreateOrEditRentProcureOrder from "./../modal/ModalCreateOrEditRentProcureOrder";
import {value} from "lodash/seq";
import ModalCreateOrEditProcureReturnOrder from "../modal/ModalCreateOrEditProcureReturnOrder";
import ModalProcureReturnOrderDetail from "../modal/ModalProcureReturnOrderDetail";

moment.locale('zh-cn');
const {RangePicker} = DatePicker;
const _ = require('lodash');
const {Option} = Select;
const table = 'ProcureMaterialReturnOrder';
const title = '采购退货';

@Form.create()
@connect(({
            user,
            global,
            dict,
            vendor,
            procure
          }) => ({...user, ...global, ...procure, ...dict, ...vendor}))
export default class ProcureReturnOfGoods extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const {dispatch} = this.props;
    const payload = this.props.form.getFieldsValue();
    _.map(payload, (value, key) => {
      if (value === '') {
        payload[key] = undefined;
      }
    });

    dispatch && dispatch({
      type: 'global/getModel',
      payload: {table}
    });

    dispatch && dispatch({
      type: 'vendor/findMany',
      payload: {}
    });

    dispatch && dispatch({
      type: 'procure/findReturnOrderMany',
      payload
    });
  }

  onDelete = record => {
    const {orderCode} = record;
    this.props.dispatch({
      type: 'procure/deleteReturnGoodsOrder',
      payload: {orderCode}
    })
      .then(res => {
        this.requestReturn(res);
        this.componentDidMount();
      });
  };

  onCreate = async (values) => {
    // notify({type: 'info', message: "待开发"});
    // return;
    let _title = values ? `编辑${title}` : `新建${title}`;
    ModalView.open(ModalCreateOrEditProcureReturnOrder, {
      title: _title,
      width: '1580px',
      maskClosable: false
    }, {
      values,
      refresh: () => {
        this.componentDidMount();
      },
      callback: (record) => {
        record.orderCode = 'PRM' + moment().format('YYYYMMDDHHmmss');
        this.props.dispatch({
          type: 'procure/createReturnGoodsOrder',
          payload: record
        }).then(res => {
          this.requestReturn(res);
          this.componentDidMount();
        });
      }
    });
  };


  getSearchFields = () => {
    return [
      <FormField
        label="编码"
        name="code"
        key={1}
      >
        <Input allowClear placeholder={`请输入${title}编码`}/>
      </FormField>,
      <FormField
        label="供应商"
        name="vendor"
        key={2}
      >
        <Input allowClear placeholder="请输入供应商"/>
      </FormField>,

      <FormField
        label="创建时间"
        name="createdTs"
        key={3}
        initialValue={[this.getSearchStart1Months(), this.getDefaultSearchEndDate()]}
      >
        <RangePicker allowClear={true}
          // style={{ width: '150%' }}
        />
      </FormField>

    ];
  };

  render() {
    const {_notify, returnOrders = {}, loading, form} = this.props;
    const {showDetail, record = {}} = this.state;


    if (_notify) {
      notify(_notify);
    }
    const {amount = 0, count = 0, list = []} = returnOrders;
    const model = this.props[`${table}Model`];
    const cols = [];

    cols.push(...this.getTableColumns(model));


    cols.push({
      title: '操作', dataIndex: 'operation', key: 'operation',
      width: 160, fixed: 'right',
      render: (value, record) => {
        return (
          <span>
            {<a style={{marginRight: '6px'}}
                onClick={() => this.setState({showDetail: true, record})}>详情</a>}
            {<a style={{marginRight: '6px'}}
                onClick={() => {
                  ModalView.open(ModalProcureReturnOrderDetail, {
                    title: "编辑",
                    width: '1080px',
                    maskClosable: false
                  }, {
                    record,
                    isEdit: true,
                    callback: (record) => {
                      this.props.dispatch({
                        type: 'procure/updateReturnGoodsOrder',
                        payload: record
                      }).then(res => {
                        this.requestReturn(res);
                        this.componentDidMount();
                      });
                    }
                  });
                }}>编辑</a>}
            {
              <Popconfirm
                title="确认删除"
                onConfirm={() => this.onDelete(record)}
                okText="是"
                cancelText="否"
              >
                <a style={{marginRight: '6px'}}>删除</a>
              </Popconfirm>
            }
            </span>
        );
      }
    });
    return (
      <div>
        <ViewTitle
          title={`采购退货列表`}
          level={1}
          actions={[
            // <Button onClick={() => this.export()}>导出</Button>,
            <Button type="primary" onClick={() => this.onCreate(undefined)}>添加</Button>]}></ViewTitle>
        <SearchForm
          style={{marginLeft: '6px', marginRight: '6px'}}
          onSearch={() => {
            this.state.current = 1;
            this.componentDidMount();
          }}
          onReset={this.handleReset}
          cols={3}
          min={6}
          expandText="展开"
          form={form}
        >
          {this.getSearchFields()}
        </SearchForm>
        <div style={{background: '#ECECEC', padding: '30px'}}>
          <Row gutter={16}>
            <Col span={12}>
              <Card>
                <Statistic
                  title="采购退货物料总数量"
                  value={count}
                  precision={2}
                  valueStyle={{color: '#3f8600'}}
                  suffix="KG"
                />
              </Card>
            </Col>
            <Col span={12}>
              <Card>
                <Statistic
                  title="采购退货物料总金额"
                  value={amount}
                  precision={2}
                  valueStyle={{color: '#cf1322'}}
                  suffix="元"
                />
              </Card>
            </Col>
          </Row>
        </div>
        <Table
          loading={loading}
          className={styles.antTable}
          bordered={true}
          columns={cols}
          dataSource={list}
          scroll={{x: true}}
          pagination={{
            current: this.state.current,
            total: this.state.total,
            showSizeChanger: true,
            onChange: page => {
              this.state.current = page;
              this.componentDidMount();
            },
            onShowSizeChange: (current, pageSize) => {
              this.state.current = 1;
              this.state.pageSize = pageSize;
              this.componentDidMount();
            }
          }}
          // pagination={{pageSize: 100}}
          //scroll={{ x: 1300 }}
        ></Table>

        {showDetail && <Drawer
          visible={showDetail}
          title={`${title}详情`}
          placement="left"
          width={'80%'}
          style={{padding: 0}}
          onClose={() => {
            this.setState({showDetail: false});
          }}
        >
          <ModalProcureReturnOrderDetail
            record={record}
          > </ModalProcureReturnOrderDetail>
        </Drawer>}

      </div>
    );
  }
}
